"""
Celery应用配置
"""

from celery import Celery
from celery.schedules import crontab
import os

from ..core.config import get_settings

settings = get_settings()

# 创建Celery应用
celery_app = Celery(
    "auto_post_tool",
    broker=settings.REDIS_URL,
    backend=settings.REDIS_URL,
    include=[
        "src.schedulers.tasks"
    ]
)

# Celery配置
celery_app.conf.update(
    # 时区设置
    timezone='Asia/Shanghai',
    enable_utc=True,
    
    # 任务序列化
    task_serializer='json',
    accept_content=['json'],
    result_serializer='json',
    
    # 任务路由
    task_routes={
        'src.schedulers.tasks.scrape_hot_trends': {'queue': 'scraper'},
        'src.schedulers.tasks.generate_content': {'queue': 'generator'},
        'src.schedulers.tasks.publish_content': {'queue': 'publisher'},
    },
    
    # 任务结果过期时间
    result_expires=3600,
    
    # 工作进程配置
    worker_prefetch_multiplier=1,
    worker_max_tasks_per_child=1000,
    
    # 定时任务配置
    beat_schedule={
        # 每30分钟抓取一次热点
        'scrape-hot-trends': {
            'task': 'src.schedulers.tasks.scrape_hot_trends',
            'schedule': crontab(minute='*/30'),
            'options': {'queue': 'scraper'}
        },
        
        # 每小时执行一次自动化流程
        'auto-workflow': {
            'task': 'src.schedulers.tasks.auto_workflow',
            'schedule': crontab(minute=0),
            'options': {'queue': 'generator'}
        },
        
        # 每天凌晨2点清理过期数据
        'cleanup-old-data': {
            'task': 'src.schedulers.tasks.cleanup_old_data',
            'schedule': crontab(hour=2, minute=0),
            'options': {'queue': 'maintenance'}
        },
        
        # 每10分钟检查系统状态
        'health-check': {
            'task': 'src.schedulers.tasks.health_check',
            'schedule': crontab(minute='*/10'),
            'options': {'queue': 'monitoring'}
        }
    },
)

# 如果禁用了调度，清空定时任务
if not settings.SCHEDULE_ENABLED:
    celery_app.conf.beat_schedule = {}